<template>
    <div class="list">
        <!-- 注意: path,params不能同时使用 -->
        <router-link class="item" v-for="(item,index) in list" :key="index" :to="{name:'detail',  params: item }">
            <div class="pic">
                <img :src="item.pic" alt="">
            </div>
            <div class="text">
                <div class="name">{{item.name}}</div>
                <div class="buycount">已售: {{item.buyCount}}件</div>
                <div class="price">单价: ¥{{item.price}}</div>
            </div>
            <div class="btn" @click="addToCart(item)">加入购物车</div>
        </router-link>
    </div>
</template>

<script>

import vm from '../../vm'
/* 从vuex导入辅助函数 */
import {mapState,mapMutations,mapActions} from 'vuex'

export default {
    data(){
        return {
            
        }
    },

    computed:{
        ...mapState(['list'])
    },
    //mapMutations是个函数,负责注入store中的同步方法(被注入的方法放到了当前组件实例身上)
    methods:{
        ...mapMutations(['addToCart']),
        ...mapActions(['request_data'])
    },
    
    mounted(){
        /* 请求数据 */
        this.request_data();

        /* 在需要接收数据的组件中,监听事件 */
        vm.$on('receiveIndex',(index)=>{
            
            console.log(index);
            //排序
            if(index == 0)//价格升序
            {
                this.list.sort(( a,b) => { return a.price - b.price  } );
            }
            else if(index == 1)//价格降序
            {
                this.list.sort(( a,b) => { return b.price - a.price  } );
            }
            else if(index == 2)//销量升序
            {
                this.list.sort(( a,b) => { return a.buyCount - b.buyCount  } );
            }
            else{//销量降序
                
                this.list.sort(( a,b) => { return b.buyCount - a.buyCount  } );
            }
        })
    }
}
</script>
<style scoped>
.list .item{
    position: relative;
    display: flex;
    margin: 20px;
}
.list .item .pic{
    width: 25%;
    margin-right: 20px;
}
.list .item .pic img{
    width: 100%;
}
.list .item .text{
    width: 75%;
}
.list .item .text .name{
    color: #333;
    white-space: nowrap;/* 文本不换行 */
    text-overflow: ellipsis;/* 文本溢出 显示省略号 */
    overflow: hidden;/* 溢出盒子,隐藏 */
}
.list .item .btn{
    position: absolute;
    right: 0;
    bottom: 0;
    background-color: red;
    color: white;
    padding: 5px 20px;
}
</style>